﻿using System;
using System.Collections.Generic;
using UnityEngine;

namespace Core
{
    public class TriggerRegion
    {
        private Queue<long> inList = new Queue<long>();
        private HashSet<long> exitList = new HashSet<long>();
        private List<Unit> enterList = new List<Unit>();

        public IReadOnlyList<Unit> GetEnterUnit()
        {
            return enterList;
        }

        public void UpdateColliders(Collider[] colliders, Func<Unit, bool> filters)
        {
            enterList.Clear();
            int i = inList.Count;
            while (i-- > 0)
            {
                exitList.Add(inList.Dequeue());
            }
            if (colliders.Length > 0)
            {
                var unitComponent = World.GetComponent<UnitComponent>();
                foreach (var collider in colliders)
                {
                    if (unitComponent.TryGetUnit(collider.transform, out var unit))
                    {
                        if (filters.Invoke(unit))
                            continue;

                        inList.Enqueue(unit.InstanceId);
                        if (!exitList.Contains(unit.InstanceId))
                        {
                            enterList.Add(unit);
                        }
                    }
                }
            }
            exitList.Clear();
        }
    }
}